package fourfaith.com.ff_sl21_app;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.HashMap;
import java.util.Map;

import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.LoadingDialog;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;

public class ModifyPwdActivity extends AppCompatActivity {

    private EditText etOldPwd,etNewPwd,etConfirmPwd;
    private Button okBtn,cancelBtn;
    private OnDialogClickListener dialogClickListener;
    private Dialog dialog;
    private JsonRequest<ResponseResult> jsonRequest;
    private CheckBox viewPwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_pwd);
        initView();
        initListeners();
    }
    public void initView(){
        etOldPwd = (EditText)findViewById(R.id.etOldPwd);
        etNewPwd = (EditText)findViewById(R.id.etNewPwd);
        etConfirmPwd = (EditText)findViewById(R.id.etConfirmPwd);
        viewPwd = (CheckBox)findViewById(R.id.viewPwd);
        okBtn =(Button)findViewById(R.id.btn_ok);
        cancelBtn = (Button)findViewById(R.id.btn_cancel);
        okBtn.setOnClickListener(updatePwd);

        viewPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    //如果选中，显示密码
                    etOldPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    etNewPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    etConfirmPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //否则隐藏密码
                    etOldPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    etNewPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    etConfirmPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

            }
        });
    }

    private View.OnClickListener updatePwd = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String _etOldPwd = etOldPwd.getText().toString();
            String _etNewPwd = etNewPwd.getText().toString();
            String _etConfirmPwd = etConfirmPwd.getText().toString();
            if (valid(_etOldPwd, _etNewPwd,_etConfirmPwd)) {
                  getModifyPwdRequest(_etOldPwd,_etNewPwd,_etConfirmPwd);
            }
        }
    };
    private void getModifyPwdRequest(final String etOldPwd,final String etNewPwd,final String etConfirmPwd) {
        RequestQueue mQueue = RequestQueueSingleton.getInstance(this).getRequestQueue();
        SharedPreferences sharedPreferences = getSharedPreferences(Constants._loginInfo, Context.MODE_PRIVATE);
        Map<String, String> params = new HashMap<>();
        params.put("userId",sharedPreferences.getString("userId",""));
        params.put("oldPassword",etOldPwd);
        params.put("newPassword",etNewPwd);

        dialog = new LoadingDialog(ModifyPwdActivity.this).setMessage("正在处理...");
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                jsonRequest.cancel();
                dialog.dismiss();
            }
        });
        dialog.show();

        jsonRequest = new JsonRequest<>(Request.Method.POST, Constants.changePwd, ResponseResult.class,
                new Response.Listener<ResponseResult>() {
                    @Override
                    public void onResponse(ResponseResult obj) {
                        if (obj.getCode().equals("200")) {
                            Toast.makeText(ModifyPwdActivity.this, "密码修改成功", Toast.LENGTH_SHORT).show();
                            finish();
                            if (dialogClickListener != null) {
                                dialogClickListener.onCancelClick();
                            }
                        }else if(obj.getCode().equals("401")){
                            Toast.makeText(ModifyPwdActivity.this, "原始密码错误", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(ModifyPwdActivity.this, obj.getMsg()+obj.getCode(), Toast.LENGTH_SHORT).show();
                        }

                        if (dialog.isShowing() && dialog != null) {
                            dialog.dismiss();
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (dialog.isShowing() && dialog != null) {
                    dialog.dismiss();
                }
                if (error.networkResponse == null) {
                    Toast.makeText(ModifyPwdActivity.this, "连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
                } else {
                    if (error.getMessage() == null) {
                        Toast.makeText(ModifyPwdActivity.this, "接口服务器异常", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ModifyPwdActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

            }

        },params);
        mQueue.add(jsonRequest);
    }
    private boolean valid(String oldPwd, String newPwd,String confirmPwd) {

        if(!Constants.isNotEmpty(oldPwd)){
            Toast.makeText(ModifyPwdActivity.this, getString(R.string.prompt_oldpwd) + "不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if(oldPwd.length()<6){
            Toast.makeText(ModifyPwdActivity.this, getString(R.string.prompt_oldpwd) + "不能小于6位", Toast.LENGTH_SHORT).show();
            return false;
        }
        if(!Constants.isNotEmpty(newPwd)){
            Toast.makeText(ModifyPwdActivity.this, getString(R.string.prompt_newpwd) +"不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if(newPwd.length()<6){
            Toast.makeText(ModifyPwdActivity.this, getString(R.string.prompt_newpwd) +"不能小于6位", Toast.LENGTH_SHORT).show();
            return false;
        }

        if(!Constants.isNotEmpty(confirmPwd)){
            Toast.makeText(ModifyPwdActivity.this, getString(R.string.prompt_confirmpwd) +"不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if(!confirmPwd.equals(newPwd)){
            Toast.makeText(ModifyPwdActivity.this, getString(R.string.prompt_pwddifferent), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
    private void initWindow() {
        //自定义windows弹窗的样式
        getWindow().setBackgroundDrawable(new ColorDrawable(0));
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN |
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    }

    private void initListeners() {
        //取消按钮取点击监听
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭当前的activity
                finish();
                if (dialogClickListener != null) {
                    dialogClickListener.onCancelClick();
                }
            }
        });
    }

    public void setOnDialogClickListener(OnDialogClickListener clickListener){
        dialogClickListener = clickListener;
    }


    public interface OnDialogClickListener{
        void onOKClick();
        void onCancelClick();
    }


}
